module V1
  class AdLandingPages < Grape::API
    # status 10-删除 1-导入 2-新建
    # 
    get 'ad_landing_page/list' do
      ad_source = AdLandingPage.where.not(status:10)
      render_json list:ad_source.page(params[:page]).per(params[:per]), count:ad_source.count
    end

    post 'ad_landing_page/create' do
      params[:status] = 2
      if params[:page_type_en] == "miniapp"
        qrcode_info = RestClient::Request.execute(
          method:  "post",
          url:     "#{ENV["crm_host"]}api/channels/generate_miniapp_qrcode",
          payload: {
            name: params[:page_name],
            platform: "miniapp", 
            page_path: params[:page_url], # 路径
            page_params:"", # 参数
            from:"" # 来源 
          },
          headers: { 'authorization': ENV["crm_authorization"]})
          params[:page_url_code] = JSON.parse(qrcode_info).fetch("image","")
      end
      render_json AdLandingPage.create(params)
    end

    post 'ad_landing_page/delete' do
      AdLandingPage.find_by(id:params[:id]).update(status:10)
      render_json
    end

    post 'ad_landing_page/update' do
      ad_page = AdLandingPage.find_by(id:params[:id])
      if params[:page_url] != ad_page[:page_url] && params[:page_type_en] == "miniapp"
        qrcode_info = RestClient::Request.execute(
          method:  "post",
          url:     "#{ENV["crm_host"]}api/channels/generate_miniapp_qrcode",
          payload: {
            name: params[:page_name],
            platform: "miniapp", 
            page_path: params[:page_url], # 路径
            page_params:"", # 参数
            from:"" # 来源 
          },
          headers: { 'authorization': ENV["crm_authorization"]})
          params[:page_url_code] = JSON.parse(qrcode_info).fetch("image","")
      end
      ad_page.update(params)
      render_json
    end
  end
end

